<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>九宫格</title>
  <style>
    .main{
      height: 0;
      width: 50%;
      position: absolute;
      padding-bottom: 50%;
      left: 25%;
      top: 25%;
    }
    .main>div{
      background: #ffa600;
      height: 0;
      width: 32%;
      padding-bottom: 32%;
      display: inline-block;
    }
  </style>
</head>
<body>
<div class="main" id="main01">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<input type="button" value="开始" onclick="startIt()"/>
<input type="button" value="结束" onclick="stopIt()"/>
<!--<input type="button" value="结束2" onclick="stopIt2()"/>-->
<script>
let recolor = "#ffa600";
let d_blocks = document.getElementById("main01").getElementsByTagName('div');
let startC = null
function startIt(){
  startC = setInterval("start0()",1000);
}

function stopIt() {
  //结束定时器
  window.clearInterval(startC);
  //清除所有方块背景颜色
  for (let i  = 0;i<d_blocks.length;i++) {
    d_blocks[i].style.backgroundColor = recolor;
  }
}

function start0() {
  //清除所有方块背景颜色
  for (let i  = 0;i<d_blocks.length;i++) {
    d_blocks[i].style.backgroundColor = recolor;
  }
  //选出9个中的随机不同的三个数--对应方块
  let arr = [];
  let tmp = {};
  for (let i = 0;i<3;i++) {
    let nub = Math.floor(Math.random()*9);
    if (!tmp[nub]) {
      arr[i] = nub;
      tmp[nub] = nub;
    } else {
      i--;
    }
  }
  //重置空对象
  tmp  = {};
  //选出三个不同的颜色；
  let carr = [];
  for (let i = 0;i<3;i++){
    let colors = castColor();
    if (colors != recolor){
      if(!tmp[colors]){
        carr[i] = colors;
        tmp[colors] = colors;
      }else{
        i--;
      }
    }else{
      i--;
    }
  }
 //将不同颜色加入到不同方块的style中
  for (let i = 0; i<3;i++){
    d_blocks[arr[i]].style.backgroundColor =  carr[i];
  }
}

function castColor() {
  let colorArr = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];
  let cast = [];
  let recast = '#';
  for (let i = 0; i<6;i++){
    cast[i] = Math.floor(Math.random()*16).toString(16);
  }
  for(let i in cast){
    recast += cast[i];
  }
  return recast;
}
</script>
</body>
</html>
